package com.zhoust.controller;

import com.zhoust.pojo.bo.ShopcartBO;
import com.zhoust.utils.IMOOCJSONResult;
import com.zhoust.utils.JsonUtils;
import com.zhoust.utils.RedisOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 15703
 */
@Api(value = "购物车接口controller", tags = {"购物车接口相关的api"})
@RequestMapping("shopcart")
@RestController
public class ShopcatController extends BaseController{

    @Autowired
    private RedisOperator redisOperator;

    @ApiOperation(value = "添加商品到购物车", notes = "添加商品到购物车", httpMethod = "POST")
    @PostMapping("/add")
    public IMOOCJSONResult add(
            @RequestParam String userId,
            @RequestBody ShopcartBO shopcartBO,
            HttpServletRequest request,
            HttpServletResponse response
    ) {

        if (StringUtils.isBlank(userId)) {
            return IMOOCJSONResult.errorMsg("");
        }

        System.out.println(shopcartBO);

        /**
         * 端用户在登录的情况下，添加商品到购物车，会同时在后端同步购物车到redis缓存
         * 1. 判断购物车是否为空，为空直接添加
         * 2. 若购物车不为空，判断商品是否已经存在，若已经存在，数量累加，如果不存在，直接添加
          */
        List<ShopcartBO> shopCartList = new ArrayList<>();
        String shopCarts = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
        if(StringUtils.isNotBlank(shopCarts)){
            // 2. 若购物车不为空，判断商品是否已经存在，若已经存在，数量累加，如果不存在，直接添加
            boolean isHave = false;
            shopCartList = JsonUtils.jsonToList(shopCarts,ShopcartBO.class);
            for (ShopcartBO scb :shopCartList) {
                if(scb.getSpecId().equals(shopcartBO.getSpecId())){
                    scb.setBuyCounts(scb.getBuyCounts()+shopcartBO.getBuyCounts());
                    isHave = true;
                }
            }
            if(!isHave){
                shopCartList.add(shopcartBO);
            }
        }else{
            // 1. 判断购物车是否为空，为空直接添加
            shopCartList.add(shopcartBO);
        }
        redisOperator.set(FOODIE_SHOPCART + ":" + userId, JsonUtils.objectToJson(shopCartList));
        return IMOOCJSONResult.ok();
    }

    @ApiOperation(value = "从购物车中删除商品", notes = "从购物车中删除商品", httpMethod = "POST")
    @PostMapping("/del")
    public IMOOCJSONResult del(
            @RequestParam String userId,
            @RequestParam String itemSpecId,
            HttpServletRequest request,
            HttpServletResponse response
    ) {

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(itemSpecId)) {
            return IMOOCJSONResult.errorMsg("参数不能为空");
        }

        /**
         *  用户在页面删除购物车中的商品数据，如果此时用户已经登录，则需要同步删除后端购物车中的商品
         * 1. 从购物车中获取数据，若为空不管（应该与cookie同步）
         * 2. 若有传入的数据，删除
         */
        List<ShopcartBO> shopCartList = new ArrayList<>();
        String shopCarts = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
        if(StringUtils.isNotBlank(shopCarts)){
            shopCartList = JsonUtils.jsonToList(shopCarts,ShopcartBO.class);
            for (ShopcartBO scb :shopCartList) {
                if(scb.getSpecId().equals(itemSpecId)){
                    //存在即删除
                    shopCartList.remove(scb);
                    break;
                }
            }
            redisOperator.set(FOODIE_SHOPCART + ":" + userId, JsonUtils.objectToJson(shopCartList));
        }

        return IMOOCJSONResult.ok();
    }

}
